package com.ibpd.shopping.web.controller.shopInterface;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.henuocms.common.IbpdCommon;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.MD5;
import com.ibpd.henuocms.common.MailTemplateUtil;
import com.ibpd.henuocms.common.MailUtil;
import com.ibpd.henuocms.web.controller.ext.FormModel;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.assist.ExtAccountEntity;
import com.ibpd.shopping.assist.InterfaceUtil;
import com.ibpd.shopping.entity.AccountEntity;
import com.ibpd.shopping.entity.FavoriteEntity;
import com.ibpd.shopping.service.account.AccountServiceImpl;
import com.ibpd.shopping.service.account.IAccountService;
import com.ibpd.shopping.service.favorite.FavoriteServiceImpl;
import com.ibpd.shopping.service.favorite.IFavoriteService;
@Controller
public class Inter_Account  extends BaseController{
	/**
	 * 注册新会员<br/>url格式:http://{域名}[:端口]/[虚拟目录/]regUser.do
	 * <br/>提交方式post
	 * <br/>数据格式:json
	 * <br/>返回值:-1:邮箱不能为空
	 * <br/>返回值:-2:用户名不能为空
	 * <br/>返回值:-3:昵称不能为空
	 * <br/>返回值:-4:密码不能为空
	 * <br/>返回值:-5:用户名已存在
	 * <br/>返回值:-6:昵称已存在
	 * <br/>返回值:-7:邮箱已经被占用
	 * <br/>返回值:0:注册成功
	 * <br/>客户端需要做相关字段的格式验证
	 * <br/>具体参数值的说明可参阅{@linkplain com.ibpd.shopping.entity.AccountEntity AccountEntity }
	 * @param resp 默认参数 不参与接口传参
	 * @param req 默认参数 不参与接口传参
	 * @param nickname 昵称
	 * @param account 会员名
	 * @param password 密码（明文）
	 * @param email 邮箱地址
	 * @throws IOException
	 */
	@RequestMapping("regUser.do")
	public void reg(HttpServletResponse resp,HttpServletRequest req,String nickname,String account,String password,String email) throws IOException{
		if(StringUtils.isBlank(email)){
			super.printMsg(resp, "-1", "-1", "邮箱不能为空");
			return;
		}
		if(StringUtils.isBlank(account)){
			super.printMsg(resp, "-2", "-1", "用户名不能为空");
			return;
		}
		if(StringUtils.isBlank(nickname)){
			super.printMsg(resp, "-3", "-1", "昵称不能为空");
			return;
		}
		if(StringUtils.isBlank(password)){
			super.printMsg(resp, "-4", "-1", "密码不能为空");
			return;
		}
		IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
		//下面这段代码用来规避因为数据库约束造成的错误
		if(accountService.checkAccountExist(account)){
			super.printMsg(resp, "-5", "-1", "id已存在");
			return;
		}
		if(accountService.checkNicknameExist(nickname)){
			super.printMsg(resp, "-6", "-1", "昵称已存在");
			return;
		}
		if(accountService.checkEmailExist(email)){
			super.printMsg(resp, "-7", "-1", "邮箱已经使用");
			return;
		}
		password=(MD5.md5(password));
		if (!StringUtils.isBlank(account)) {
			// 用户注册
			AccountEntity accountEntity=new AccountEntity();
			accountEntity.setAccount(account);
			accountEntity.setNickname(nickname);
			accountEntity.setPassword(password);
			accountEntity.setEmail(email);
			accountService.saveEntity(accountEntity);
			//发送邮件到用户的邮箱
			String to = email;
			
			MailUtil mail=new MailUtil(to);
//			mail.attachfile("e:\\1.jpg");
//			mail.attachfile("e:\\bsa.js");
//			mail.attachfile("e:\\aa.txt");
			mail.startSend("手尚功夫用户注册确认邮件",MailTemplateUtil.getInterface().getMailContent("accountReg",accountEntity));
			super.printMsg(resp, "0", "0", "注册成功");
		}else{
			super.printMsg(resp, "-2", "-2", "ID不能为空");
			return;
		}

	}
	/**
	 * 支持通过account或email登录
	 * @param resp
	 * @param req
	 * @param account
	 * @param email
	 * @param password
	 * @throws IOException 
	 */
	@RequestMapping("userLogin.do")
	public void userLogin(HttpServletResponse resp,HttpServletRequest req,String account,String email,String password) throws IOException{
		Boolean tmp_acc=false;
		Boolean tmp_email=false;
		if(!StringUtils.isBlank(account))
			tmp_acc=true;
		if(!StringUtils.isBlank(email))
			tmp_email=true;
		if(tmp_acc || tmp_email){
			IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
			AccountEntity acc=null;
			if(tmp_acc){
				acc=accountService.getAccountByAccount(account);
			}else{
				acc=accountService.getAccountByEmail(email);
			}
			if(acc==null){
				super.printMsg(resp, "-1", "-1", "没有该用户信息");
			}else{
				String newPass=MD5.md5(password);
				if(acc.getPassword().equals(newPass)){
					InterfaceUtil.setLoginUserInfoToSession(req.getSession(), acc);
					super.printMsg(resp, "0", acc.getId().toString(), "登陆成功");
				}else{
					super.printMsg(resp, "-3", "-3", "密码错误");
				}
			}
		}else{
			super.printMsg(resp, "-2", "-2", "用户名或邮箱地址必须至少填写一项");
		}
	}
	@RequestMapping("checkUserLoginState.do")
	public void checkUserLoginState(HttpServletResponse resp,HttpServletRequest req) throws IOException{
		AccountEntity acc=InterfaceUtil.getLoginedAccountInfo(req);
		if(acc==null){
			super.printMsg(resp, "-1", "-1", "尚未登录或登录已经失效");
		}else{
			InterfaceUtil.setLoginUserInfoToSession(req.getSession(), acc);//这里重新设置一次，延长session保留时间，防止前几秒检测用户状态正常，后几秒就失效的状况
			super.printMsg(resp, "0", "0", "登陆成功");
		}
	}
	@RequestMapping("userLogout.do")
	public void userLogout(HttpServletResponse resp,HttpServletRequest req) throws IOException{
		InterfaceUtil.setLoginUserInfoToSession(req.getSession(), null);
		super.printMsg(resp, "1", "0", "注销成功");
	}
	@RequestMapping("feedback.do")
	public void feedback(HttpServletResponse resp,HttpServletRequest req,String tel,String content) throws IOException{
		if(StringUtil.isBlank(tel) || StringUtil.isBlank(content)){
			super.printMsg(resp, "-1", "0", "手机号和内容都是必填项.");
			return;
		}
		MailUtil m=new MailUtil( IbpdCommon.getInterface().getPropertiesValue("feedback_email_address"));
		m.startSend(tel+"发来的反馈意见", content);
		super.printMsg(resp, "1", "0", "提交成功");
	}
	@RequestMapping("changeNickName.do")
	public void changeNickName(HttpServletResponse resp,HttpServletRequest req,String nickName) throws IOException{
		AccountEntity acc=InterfaceUtil.getLoginedAccountInfo(req);
		if(acc==null){
			super.printMsg(resp, "-1", "-1", "尚未登录或登录已经失效");
		}else{
			IAccountService as=(IAccountService) getService(AccountServiceImpl.class);
			AccountEntity a=as.getEntityById(acc.getId());
			if(a==null){
				super.printMsg(resp, "-1", "0", "参数错误");
				return;
			}
			if(StringUtil.isBlank(nickName)){
				super.printMsg(resp, "-1", "0", "参数不能为空");
				return;
			}
			a.setNickname(nickName);
			as.saveEntity(a);
			super.printMsg(resp, "1", "0", "提交成功");
		}
		
	}
	@RequestMapping("forgetPassword.do")
	public void forgetPassword(HttpServletRequest req,HttpServletResponse resp,String account,String email) throws IOException{
		if(StringUtils.isBlank(account) || StringUtils.isBlank(email)){
			super.printMsg(resp, "-1", "-1", "用户名或邮箱地址必须填写");
			return;
		}
		IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity acc=accountService.getAccountByAccount(account);
		if(acc==null){
			super.printMsg(resp, "-2", "-2", "没有该用户");
			return;
		}
		if(acc.getEmail().trim().toLowerCase().equals(email.trim().toLowerCase())){
			Integer newpsd=(int)((Math.random()*9+1)*100000);
			acc.setPassword(newpsd.toString());
			IbpdLogger.getLogger(this.getClass()).info(newpsd);
			MailUtil mail=new MailUtil(email);//将来替换了或走配置文件获取
			mail.startSend("手尚功夫用户密码找回",MailTemplateUtil.getInterface().getMailContent("forgetPassword",acc));
			acc.setPassword(MD5.md5(newpsd.toString()));
			accountService.saveEntity(acc);
			super.printMsg(resp, "0", "0", "新密码已经发送至邮箱");
		}else{
			super.printMsg(resp, "-3", "-3", "邮箱地址与用户名不匹配");
		}

	}
	@RequestMapping("changePassword.do")
	public void changePassword(HttpServletResponse resp,HttpServletRequest req,String account,String oldPassword,String newPassword) throws IOException{
		if(StringUtils.isBlank(account) || StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)){
			super.printMsg(resp, "-1", "-1", "用户名、旧密码、新密码三项必须填写");
			return;
		}
		if(newPassword.trim().length()<6){
			super.printMsg(resp, "-4", "-4", "密码长度必须大于等于6位字符");
			return;
		}
		IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity acc=accountService.getAccountByAccount(account);
		if(acc==null){
			super.printMsg(resp, "-2", "-2", "没有该用户");
			return;
		}
		if(acc.getPassword().equals(MD5.md5(oldPassword))){
			acc.setPassword(MD5.md5(newPassword));
			accountService.saveEntity(acc);
			super.printMsg(resp, "0", "0", "密码修改成功");
		}else{
			super.printMsg(resp, "-3", "-3", "旧密码不匹配");
		}
	}
	@RequestMapping("getAccountInfo.do")
	public void getAccountInfo(HttpServletResponse resp,HttpServletRequest req) throws IOException{
		AccountEntity acc=InterfaceUtil.getLoginedAccountInfo(req);
		if(acc==null){
			super.printMsg(resp, "-1", "-1", "用户尚未登录");
			return;
		}
		IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
		acc=accountService.getAccountByAccount(acc.getAccount());
		if(acc==null){
			super.printMsg(resp, "-2", "-2", "没有该用户");
			return;
		}
		acc.setLastLoginTime(new Date());
		accountService.saveEntity(acc);
		ExtAccountEntity ext=new ExtAccountEntity(acc);
		ext.setFavoriteProductCount(getFavoriteCount(acc.getId(),"product"));
		ext.setFavoriteTenantCount(getFavoriteCount(acc.getId(),"tenant"));
		List accList=new ArrayList();
		accList.add(ext);
		super.sendJsonByList(resp, accList, 1L);
	}
	private Integer getFavoriteCount(Long accId,String type){
		IFavoriteService favServ=(IFavoriteService) getService(FavoriteServiceImpl.class);
		String hql="from "+favServ.getTableName()+" where accId="+accId+" and type=" ;
		if(type.trim().toLowerCase().equals("product")){
			hql+=FavoriteEntity.TYPE_PRODUCT;
		}else{
			hql+=FavoriteEntity.TYPE_TENANT;
		} 
		List s=favServ.getList(hql, null);
		if(s==null)
			return 0;
		return s.size();
	}
	@RequestMapping("updateAccountInfo.do")
	public void updateAccountInfo(HttpServletResponse resp,HttpServletRequest req,@FormModel("account")AccountEntity account) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(account!=null){
			if(account.getId()!=null && account.getId()!=-1){
				IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
				AccountEntity acc=accountService.getEntityById(account.getId());
				if(acc==null){
					super.printMsg(resp, "-2", "-2", "没有该用户");
					return;
				}else{
					String _account=acc.getAccount();
					String _email=acc.getEmail();
					String _password=acc.getPassword();
					swap(account,acc);
					acc.setAccount(_account);
					acc.setEmail(_email);
					acc.setPassword(_password);
					accountService.saveEntity(acc);
					super.printMsg(resp, "0", "0", "修改成功");
				}

			}else
				super.printMsg(resp, "-2", "-2", "post参数错误(ID值错误)");
		}else
			super.printMsg(resp, "-2", "-2", "post参数错误(没有获取到参数)");
	}
	private void swap(AccountEntity formAcc,AccountEntity dbAcc) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Method[] methods=formAcc.getClass().getMethods();
		for(Method getMethod:methods){
			String getMethodName=getMethod.getName();
			if(getMethodName.substring(0,3).equals("get") && !getMethodName.equals("getClass")){
				String setMethodName="set"+getMethodName.substring(3);
				Method setMethod=dbAcc.getClass().getMethod(setMethodName, getMethod.getReturnType());
				if(setMethod!=null){
					setMethod.invoke(dbAcc, getMethod.invoke(formAcc, null));
				}
			}
		}
	}
	@RequestMapping("changeAccountHeadImage.do")
	public void changeAccountHeadImage(String headUrl,HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		AccountEntity acc=InterfaceUtil.getLoginedAccountInfo(request);
		if(acc==null){
			super.printMsg(response, "-1", "-1", "用户尚未登录");
		}
		IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
		acc=accountService.getAccountByAccount(acc.getAccount());
		if(acc==null){
			super.printMsg(response, "-2", "-2", "没有该用户");
			return;
		}
		if(StringUtils.isBlank(headUrl)){
			super.printMsg(response, "-3", "-3", "参数错误");
			return;
		}
		IAccountService as=(IAccountService) getService(AccountServiceImpl.class);
		AccountEntity a=as.getEntityById(acc.getId());
		if(a==null){
			super.printMsg(response, "-2", "-2", "没有该用户");
			return;
		}
		a.setLogo(headUrl);
		as.saveEntity(a);
		super.printMsg(response, "1", "1", "保存成功");
		return;
		
	}
	@RequestMapping("doUpload.do")
	public void doUpload(String fileUploadDir,HttpServletRequest request,
			HttpServletResponse response) throws IOException {
//		AccountEntity acc=InterfaceUtil.getLoginedAccountInfo(request);
//		if(acc==null){
//			super.printMsg(response, "-1", "-1", "用户尚未登录");
//		}
//		IAccountService accountService=(IAccountService) getService(AccountServiceImpl.class);
//		acc=accountService.getAccountByAccount(acc.getAccount());
//		if(acc==null){
//			super.printMsg(response, "-2", "-2", "没有该用户");
//			return;
//		}
		fileUploadDir = fileUploadDir==null?"/uploadFiles":fileUploadDir;
		fileUploadDir = StringUtils.isBlank(fileUploadDir)?"/uploadFiles":fileUploadDir;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
		String basePath = request.getRealPath(fileUploadDir);
		File fbasePath = new File(basePath);
		if (!fbasePath.exists())
			fbasePath.mkdirs();
		factory.setRepository(fbasePath);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(1024 * 1024 * 100);
		// 设置整个request的最大值
		upload.setSizeMax(1024 * 1024 * 100 * 20);
		upload.setHeaderEncoding("UTF-8");

		try {
			List<?> items = upload.parseRequest(request);
			FileItem item = null;
			String fileName = null;
			item = (FileItem) items.get(0);
			String newFileName = getNewName(item.getName());
			fileName = basePath + File.separator + newFileName;
			if (!item.isFormField() && item.getName().length() > 0) {
				item.write(new File(fileName));
				super.printMsg(response, "1", "1", request.getContextPath()+"/"+fileUploadDir + "/"
						+ newFileName);
				return;
			} else {
				super.printMsg(response, "-3", "-3", "未检测到可上传文件");
				return;
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.printMsg(response, "-3", "-3", "未检测到可上传文件");
	}

	private String getNewName(String fName){
		String ext=fName.substring(fName.lastIndexOf("."));
		String ff = UUID.randomUUID().toString()+ext;
		return ff;
	}
}
